package castle.defense.project;

import android.content.Context;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * Basic view object that holds the game, as well as manages the touch events (passes them onto the thread).
 * 
 * @author Daniel Wasserman
 *
 */
public class GameView extends SurfaceView implements SurfaceHolder.Callback, OnTouchListener, GestureDetector.OnGestureListener {
	
	private GameThread thread;
	private GestureDetector mGestureDetector;
	
	public GameView(Context context) {
		super(context);
		this.setPadding(5, 50, 64, 0);
		SurfaceHolder s = this.getHolder();
		s.addCallback(this);
		this.setFocusable(true);
		thread = new GameThread(s,context);
		this.setOnTouchListener(this);
		mGestureDetector = new GestureDetector(context, this);
	}
	
	public void stop() {
		thread.setRunning(false);
	}
	
	public void surfaceChanged(SurfaceHolder s, int format, int width, int height) {
		thread.setSurfaceHolder(s);
		PE.setBounds(s.getSurfaceFrame().width(), s.getSurfaceFrame().height());
	}

	public void surfaceCreated(SurfaceHolder s) {
		PE.setBounds(s.getSurfaceFrame().width(), s.getSurfaceFrame().height());
		GraphicsEngine.initialize();
		thread.setSurfaceHolder(s);
		thread.start();
	}

	public void surfaceDestroyed(SurfaceHolder s) {
		thread.setRunning(false);
	}
	
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float xV, float yV) {
		return true;
	}
	
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {
//		thread.inverserPausedState();
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float xV, float yV) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return thread.onSingleTap(e);
	}
	
	//let gesture detector handle the onTouchEvents
	public boolean onTouchEvent(MotionEvent e) {
		return true;
	}
	@Override
	public boolean onTouch(View v, MotionEvent e) {
		return mGestureDetector.onTouchEvent(e);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent e) {
		
		if(keyCode==KeyEvent.KEYCODE_MENU && e.getAction()==KeyEvent.ACTION_DOWN)
			thread.inversePausedState();
		
		return super.onKeyDown(keyCode, e);
	}
}